from conan import ConanFile
from conan.tools.cmake import CMake, CMakeDeps, CMakeToolchain, cmake_layout
from conan.tools.files import apply_conandata_patches, copy, export_conandata_patches, get, replace_in_file, rm, rmdir, rename
from conan.tools.microsoft import is_msvc
import os

class LuaCjsonConan(ConanFile):
    name = "lua-cjson"
    description = "lua cjson parse"
    license = "MIT license"
    url = "https://github.com/conan-io/conan-center-index"
    homepage = "https://www.kyne.com.au/~mark/software/lua-cjson.php"
    topics = ("lua", "cjson parse")
    package_type = "library"
    settings = "os", "arch", "compiler", "build_type"
    options = {
        "shared": [True, False],
        "fPIC": [True, False],
    }
    default_options = {
        "shared": False,
        "fPIC": True,
    }
    
    def export_sources(self):
        export_conandata_patches(self)

    def config_options(self):
        if self.settings.os == "Windows":
            del self.options.fPIC

    def configure(self):
        if self.options.shared:
            self.options.rm_safe("fPIC")
            
    def requirements(self):
        self.requires("luajit/2.1.0-beta3")

    def layout(self):
        cmake_layout(self, src_folder=".")

    def source(self):
        get(self, **self.conan_data["sources"][self.version],
            destination=self.source_folder, strip_root=True)

    def generate(self):
        tc = CMakeToolchain(self)
        tc.generate()
        deps = CMakeDeps(self)
        deps.generate()
        
    def _patch_sources(self):
        apply_conandata_patches(self)
        
    def build(self):
        self._patch_sources()
        cmake = CMake(self)
        cmake.configure()
        cmake.build()

    def package(self):
        copy(self, "LICENSE", src=self.source_folder, dst=os.path.join(self.package_folder, "licenses"))
        cmake = CMake(self)
        cmake.install()

    def package_info(self):
        self.cpp_info.set_property("cmake_file_name", "cjson")
        self.cpp_info.set_property("cmake_target_name", "cjson::cjson")
        self.cpp_info.set_property("pkg_config_name", "cjson")
        self.cpp_info.libs = ["cjson"]
        
        self.cpp_info.names["cmake_find_package"] = "cjson"
        self.cpp_info.names["cmake_find_package_multi"] = "cjson"
